#!/bin/sh

iptables -D INPUT -p tcp --dport 1723 -m comment --comment "PPTP VPN Server" -j ACCEPT 2> /dev/null
pptp_nums=$(iptables -t nat -n -L POSTROUTING 2>/dev/null | grep -c "PPTP VPN Server")
if [ -n "$pptp_nums" ]; then
	until [ "$pptp_nums" = 0 ]
	do
		pptp_rules=$(iptables -t nat -n -L POSTROUTING --line-num 2>/dev/null | grep "PPTP VPN Server" | awk '{print $1}')
		for pptp_rule in $pptp_rules
		do
			iptables -t nat -D POSTROUTING $pptp_rule 2> /dev/null
			break
		done
		pptp_nums=$(expr $pptp_nums - 1)
	done
fi
nums=$(iptables -n -L forwarding_rule 2>/dev/null | grep -c "PPTP VPN Server")
if [ -n "$nums" ]; then
	until [ "$nums" = 0 ]
	do
		rules=$(iptables -n -L forwarding_rule --line-num 2>/dev/null | grep "PPTP VPN Server" | awk '{print $1}')
		for rule in $rules
		do
			iptables -D forwarding_rule $rule 2> /dev/null
			break
		done
		nums=$(expr $nums - 1)
	done
fi

enable=$(uci -q get pptpd.pptpd.enabled)
if [ -n "$enable" -a "$enable" == 1 ]; then
	localip=$(uci -q get pptpd.pptpd.localip)
	iptables -t nat -I POSTROUTING -s ${localip%.*}.0/24 -m comment --comment "PPTP VPN Server" -j MASQUERADE
	iptables -I forwarding_rule -s ${localip%.*}.0/24 -m comment --comment "PPTP VPN Server" -j ACCEPT
	iptables -I INPUT -p tcp --dport 1723 -m comment --comment "PPTP VPN Server" -j ACCEPT 2>/dev/null
fi
